package com.yuanfeng.goods.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.StringUtils;
import com.yuanfeng.commoms.vo.goods.*;
import com.yuanfeng.commoms.vo.shop.ManageShopSelfCatMenuVO;
import com.yuanfeng.goods.dto.ManageByTypeIdParamInfoDTO;
import com.yuanfeng.goods.entity.GoodsPropertyEntity;
import com.yuanfeng.goods.entity.GoodsTypeEntity;
import com.yuanfeng.goods.mapper.GoodsPropertyMapper;
import com.yuanfeng.goods.mapper.GoodsTypeMapper;
import com.yuanfeng.goods.service.GoodsPropertyService;
import com.yuanfeng.goods.vo.GdbMerchantGoodsSpecPitchVO;
import com.yuanfeng.goods.vo.ManageGdsAddVo;
import com.yuanfeng.goods.vo.ManageGoodsFormatQueryParamVO;
import com.yuanfeng.goods.vo.ManageSpecValueResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class GoodsPropertyServiceImpl extends ServiceImpl<GoodsPropertyMapper, GoodsPropertyEntity>
    implements GoodsPropertyService{

    @Autowired
    private GoodsTypeMapper goodsTypeMapper;
    @Override
    public ResponseResult deteleGoodsProperty(Map<String, Object> param) {
        this.baseMapper.deleteById(Integer.valueOf(param.get("propertyId").toString()));
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult addGoodsProperty(Map<String, Object> param) {
        if (null == param.get("typeId")) {
            List<Integer> typeIds = goodsTypeMapper.selectList(new LambdaQueryWrapper<GoodsTypeEntity>()
                                    .orderByDesc(GoodsTypeEntity::getTypeId)).stream().map(GoodsTypeEntity::getTypeId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(typeIds)) {
                GoodsTypeEntity addparam = new GoodsTypeEntity();
                goodsTypeMapper.insert(addparam);
                GoodsPropertyEntity entity=new GoodsPropertyEntity();
                Integer typeId = addparam.getTypeId();
                entity.setTypeId(typeId);
                this.baseMapper.insert(entity);
            } else {
                param.put("typeId",typeIds.get(0));
                if (null == param.get("propertyId")) {
                    this.baseMapper.insertGoodsProperty(param);
                } else {
                    this.baseMapper.updateGoodsProperty(param);
                }
            }

        } else {
            if (null == param.get("propertyId")) {
                this.baseMapper.insertGoodsProperty(param);
            } else {
                this.baseMapper.updateGoodsProperty(param);
            }
        }

        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult queryByTypeId(ManageByTypeIdParamInfoDTO param) {
        // 封装返回结果
        ManageGdsAddVo manageGdsAddResult = new ManageGdsAddVo();

        Integer typeId = Integer.valueOf(param.getTypeId());
        String gooddId =param.getGoodsId();

        //根据goodsid查询商品规格
        Map map = this.baseMapper.selShopIdBygoodsId(gooddId);
        Integer shopId = Integer.valueOf(map.get("shop_id").toString());
        String specvalue1 = String.valueOf(map.get("spec_value"));

        List<GoodBaseSpecValuesJsonBeanVO> specValuesJsonBeans = new ArrayList<>();
        JSONArray specValuesJsonBeanArray = com.alibaba.fastjson.JSONObject.parseArray(specvalue1);
        for(int index = 0;index < specValuesJsonBeanArray.size();index++) {
            com.alibaba.fastjson.JSONObject obj = specValuesJsonBeanArray.getJSONObject(index);
            GoodBaseSpecValuesJsonBeanVO temp = JSONObject.parseObject(obj.toJSONString(), GoodBaseSpecValuesJsonBeanVO.class);
            specValuesJsonBeans.add(temp);
        }
        manageGdsAddResult.setSpecValueList(specValuesJsonBeans);
        // 根据typeId查询属性名
        List<ManagePropertyValueVO> propertyNames = this.baseMapper.selectByTypeId2(typeId);
        // 根据typeId查询规格名称和id
        List<ManageSpecNameVO> specvalue = this.baseMapper.selectByTypeId(typeId);

        // 根据店铺id查询规格列表
        ManageByTypeIdParamInfoDTO manageSpecValueQuery = new ManageByTypeIdParamInfoDTO();
        manageSpecValueQuery.setShopId(shopId);
        manageSpecValueQuery.setCatId(param.getCatId());
        manageSpecValueQuery.setTypeId(param.getTypeId());
        StringBuilder specIdVar = new StringBuilder();
        List<String> specIdStringList = new ArrayList<>();
        for (ManageSpecNameVO specValueQuery :specvalue){
            specIdStringList.add(specValueQuery.getSpecId().toString());

        }
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < specIdStringList.size(); i++) {
            //该步即不会第一位有逗号，也防止最后一位拼接逗号！
            if (sb.length() > 0) {
                sb.append(",");
            }
            sb.append(specIdStringList.get(i));
        }
        System.out.println(sb.toString());
        manageSpecValueQuery.setSpecId(sb.toString().trim());
        System.out.println(manageSpecValueQuery.getSpecId());
        List<ManageSpecValueResultVO> manageSpecValueResultParams =new ArrayList<>();
        manageSpecValueResultParams = this.baseMapper.selectByResultParam(manageSpecValueQuery);
        if (manageSpecValueResultParams==null ||manageSpecValueResultParams.isEmpty() ){
            manageSpecValueResultParams = this.baseMapper.selectByResultParam2(manageSpecValueQuery);
        }
        GdbMerchantGoodsSpecPitchVO goodsSpecPitch =new GdbMerchantGoodsSpecPitchVO();
        List<String> list = new ArrayList<>();
        if (null!=param.getGoodsId()){
            goodsSpecPitch = this.baseMapper.selectGoodsSpecPitch(param.getGoodsId());
            String var1=goodsSpecPitch.getGoodsSpec();
            String[] split =var1.split("\\+");
            for (String  var: split) {
                list.add(var);
            }
        }

        Map<String, List<Map<String, Object>>> specNameMap = new HashMap<>();
        // 过滤相同得规格
        for(ManageSpecValueResultVO record : manageSpecValueResultParams) {
            specNameMap.put(record.getSpecName(), null);
        }
        List<Map<String, Object>> listMap = null;
        for(ManageSpecValueResultVO record : manageSpecValueResultParams) {
            listMap = specNameMap.get(record.getSpecName());
            if(null == listMap) {
                listMap = new ArrayList<>();
            }
            Map<String, Object> specNameM = new HashMap<>();
            specNameM.put("goodsId", record.getGoodsId());
            System.out.println(record.getSpecValueName());
            specNameM.put("specValueName", record.getSpecValueName());
            specNameM.put("commonId", goodsSpecPitch.getCommonId());
            specNameM.put("marking", "false");
            for (String flags :list){
                if (flags.equals(record.getSpecValueName())){
                    specNameM.put("marking", "true");
                }
            }

            listMap.add(specNameM);
            specNameMap.put(record.getSpecName(), listMap);
        }

        List<ManageGoodsSpecValueVO> specValueNameList =new ArrayList<>();
        if (null != specvalue && !specvalue.isEmpty()) {
            for (ManageSpecNameVO specValueResult : specvalue) {
//                    List<String> varList =goodsSpecValueMapper.selectListBysprcId(specValueResult.getSpecId());
                specValueResult.setSpecValueNames(specNameMap.get(specValueResult.getSpecName()));
            }
        }

        // 获取运费模板
        List<ManageTransportTemplateResultVO> transportTemplate = this.getTransportTemplate(shopId);
        // 查询店铺自定义商品分类
        List<ManageShopSelfCatMenuVO> shopSelfCatMenu = this.getShopSelfCatMenu(shopId);
        // 查询关联板式
        ManageGoodsFormatQueryParamVO goodsFormatParam = new ManageGoodsFormatQueryParamVO();
        goodsFormatParam.setShopId(shopId);



        manageGdsAddResult.setPropertyNames(propertyNames);
        manageGdsAddResult.setSpecValueName(specvalue);
        manageGdsAddResult.setSpecValues(specValueNameList);

        manageGdsAddResult.setTransportTemplate(transportTemplate);
        manageGdsAddResult.setShopSelfCatMenu(shopSelfCatMenu);

        return ResponseResult.success(manageGdsAddResult);
    }

    /**
     * 查询运费模板
     *
     * @param shopId
     * @return
     */
    private List<ManageTransportTemplateResultVO> getTransportTemplate(Integer shopId) {
        List<ManageTransportTemplateResultVO> transportTemplates = this.baseMapper.selectByShopId(shopId);
        return transportTemplates;
    }

    /**
     * 查询店铺自定义商品分类
     *
     * @param shopId
     * @return
     */
    private List<ManageShopSelfCatMenuVO> getShopSelfCatMenu(Integer shopId) {
        // 获取所有的分类
        List<ManageShopSelfCatMenuVO> rootMenus = this.baseMapper.selectByShopIdCat(shopId);
        // 获取多级分类
        List<ManageShopSelfCatMenuVO> menuList = getMenuList(rootMenus);
        return menuList;
    }

    /**
     * 找出一级菜单和二级菜单
     *
     * @param rootMenus
     * @return
     */
    public List<ManageShopSelfCatMenuVO> getMenuList(List<ManageShopSelfCatMenuVO> rootMenus) {
        List<ManageShopSelfCatMenuVO> list = new ArrayList<ManageShopSelfCatMenuVO>();
        // 先找到所有的一级菜单
        for (int i = 0; i < rootMenus.size(); i++) {
            ManageShopSelfCatMenuVO menu = rootMenus.get(i);
            // 一级菜单 没有父节点
            if (menu.getParentId() == 0) {
                list.add(menu);
            }
        }

        // 查找二级菜单
        /**
         * 利用递归找出所有子菜单
         */
        for (ManageShopSelfCatMenuVO menu : list) {
            menu.setChildren(getChild(menu.getShopGoodsCatId(), rootMenus));
        }

        return list;

    }

    /**
     * 找出子菜单
     *
     * @param id
     * @param rootMenu
     * @return
     */
    private List<ManageShopSelfCatMenuVO> getChild(Integer parentId, List<ManageShopSelfCatMenuVO> rootMenu) {
        // 子菜单
        List<ManageShopSelfCatMenuVO> childList = new ArrayList<ManageShopSelfCatMenuVO>();

        for (ManageShopSelfCatMenuVO menu : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (!StringUtils.isEmpty(menu.getParentId().toString())) {
                if (menu.getParentId().equals(parentId)) {
                    childList.add(menu);
                }
            }
        }

        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }

        // 把子菜单的子菜单再循环一遍
        for (ManageShopSelfCatMenuVO menu : childList) {
            // 递归
            menu.setChildren(getChild(menu.getShopGoodsCatId(), rootMenu));
        }

        return childList;
    }
}




